#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
 @file name: tasks.py
 @desc:
 @author: xu wang
 @mail: jason_wangxu@163.com
 @date: 2025/1/6 14:52
"""
from ApiTestEngine.core2.cases import run_test
from rest_framework.response import Response

from Scenes.serializers import TestSceneRunSerializer
from TestTask.models import TestTask, TestRecord, TestReport
from Testproject.models import TestEnvModel
from interfaceTestPlatform.celery import celery_app


@celery_app.task
def run_test_task(env_id, task_id, tester):
    env = TestEnvModel.objects.get(id=env_id)
    env_config = {
        "ENV": {
            "host": env.host,
            "headers": env.headers,
            **env.global_variable
        },
        "DB": env.db,
        "global_func": env.global_func
    }
    # 组装case_config
    task = TestTask.objects.get(id=task_id)
    scene_list = task.scene.all()
    case_data = []
    for scene in scene_list:
        case = scene.testscenetocase_set.all()
        res = TestSceneRunSerializer(case, many=True).data
        datas = sorted(res, key=lambda x: x["sort"])
        case_data.append({
            "name": scene.name,
            "Cases": [x["icase"] for x in datas]
        })
    # 写测试记录
    """
     | 字段          | 类型         | 空   | 默认  | 注释      |
     |:----------- |:---------- |:--- | --- | ------- |
     | id          | int        | 否   |     | 自增长主键ID |
     | task        | ForeignKey | 否   |     | 执行的测试任务 |
     | all         | int        | 是   | 0   | 用例总数    |
     | success     | int        | 是   | 0   | 成功用例数   |
     | fail        | int        | 是   | 0   | 失败用例数   |
     | error       | int        | 是   | 0   | 错误用例数   |
     | pass_rate   | varchar    | 是   | '0' | 通过率     |
     | tester      | varchar    | 是   |     | 执行者     |
     | env         | ForeignKey | 否   |     | 测试环境    |
     | statue      | varchar    | 否   |     | 执行状态    |
     | create_time | DataTime   | 否   |     | 执行时间    |

     """

    obj = TestRecord.objects.create(task=task, env=env, statue="执行中", tester=tester)
    r = run_test(env_config=env_config, case_data=case_data, debug=False)
    TestReport.objects.create(info=r, record=obj)
    # 更新测试记录
    obj.all = r["all"]
    obj.success = r["success"]
    obj.fail = r["fail"]
    obj.error = r["error"]
    obj.pass_rate = "%.1f" % (r["success"] / r["all"])
    obj.save()
    return r
